package com.example.e.Fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.e.Adapter.ShopAdapter
import com.example.e.Bean.Shop
import com.example.e.FoodActivity
import com.example.e.HttpUse.HttpUtil
import com.example.e.HttpUse.IP
import com.example.e.LocationActivity
import com.example.e.R
import com.example.e.SearchActivity
import com.example.e.data.DataBean
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.fragment_home.*
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.json.JSONArray
import java.io.IOException
import java.util.*

class HomeFragment : Fragment(){

    private val shopList:ArrayList<Shop> = ArrayList<Shop>()
    val updateText = 1

    val get_all_shop = "${IP.ServerIP}e/shop/get_all_shop_json.jsp"

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        var view = inflater.inflate(R.layout.fragment_home, container, false)

        return view
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //定位
        var mLocation = view.findViewById(R.id.location) as TextView
        mLocation.setOnClickListener(){
            val intent = Intent(activity,LocationActivity::class.java)
            startActivity(intent)
        }
        //搜索框
        var searchshop = view.findViewById(R.id.tv_search_bg) as TextView
        searchshop.setOnClickListener(){
            val intent = Intent(activity,SearchActivity::class.java)
            startActivity(intent)
        }

        //轮播图
        var banner: Banner<DataBean, BannerImageAdapter<DataBean>> = view.findViewById(R.id.banner)
        banner.setAdapter(object : BannerImageAdapter<DataBean>(DataBean.testData3) {
            override fun onBindView(
                holder: BannerImageHolder,
                data: DataBean,
                position: Int,
                size: Int
            ) {

                //图片加载自己实现
                Glide.with(holder.itemView)
                    .load(data.imageUrl)
                    .apply(RequestOptions.bitmapTransform(RoundedCorners(30)))
                    .into(holder.imageView)
            }

        }).addBannerLifecycleObserver(this).setIndicator(CircleIndicator(activity))
        //推荐商家布局管理器
        val layoutManager = LinearLayoutManager(activity)
        recyclerviewShop.layoutManager = layoutManager
        val adapter = ShopAdapter(shopList)

        //okHttp回调  显示首页的推荐商家
        HttpUtil.sendByOkHttp(get_all_shop,object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val responseData = response.body!!.string()
                val result = parseJson(responseData)
                activity?.runOnUiThread {
                    recyclerviewShop.adapter = adapter
                    // tvResponse.text = responseData
                }
            }

            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }
        })

        adapter.onItemClick = {v,pos->
            val intent = Intent(activity, FoodActivity::class.java)
            startActivity(intent)
        }
    }
    private fun parseJson(jsonStr:String):ArrayList<Shop>{
        shopList.clear()
        val builder = StringBuilder()
        try {
            //json数组
            val jsonArray = JSONArray(jsonStr)
            for(i in 0 until jsonArray.length()){
                //元素取出
                val jsonObject = jsonArray.getJSONObject(i)
                val id = jsonObject.getInt("id")
                val name = jsonObject.getString("name")
                val imageURL = jsonObject.getString("imageURL")
                val score = jsonObject.getString("score")
                val sale = jsonObject.getString("sale")
                val sprice = jsonObject.getString("sprice")
                val dprice = jsonObject.getString("dprice")
                val distance = jsonObject.getString("distance")
                val time = jsonObject.getString("time")
                shopList.add(Shop(name,imageURL,score,sale,sprice,dprice,distance,time))
                //Toast.makeText(this,"${imageURL}", Toast.LENGTH_LONG).show()
                builder.append("$name--$imageURL--")
            }
        }catch (e: Exception){
            e.printStackTrace()
        }
        return shopList
    }
}